package com.github.llyb120.szuniver.document.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.github.llyb120.json.Arr;
import com.github.llyb120.json.TypeReference;
import com.github.llyb120.szuniver.document.entity.Category;
import com.github.llyb120.szuniver.document.entity.CategoryTree;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.ReplaceOptions;
import lombok.var;
import org.bson.Document;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;

import static com.github.llyb120.json.Json.*;
import static com.github.llyb120.namilite.NamiBaseController.error;

/**
 * @Author: Administrator
 * @Date: 2020/9/24 10:26
 */
@Service
public class CategoryService {
    @Resource
    MongoDatabase db;

    public static final String COL_CATEGORY = "t_category";
    public static final String ERR_SAME_NAME = "分类名重复";


    public boolean save(Category category) {
        if (StrUtil.isBlank(category.getId())) {
            category.setId(IdUtil.objectId());
        }
        //同分类下不能有相同的
        long count = db.getCollection(COL_CATEGORY)
            .countDocuments(bo(
                "id", o("$ne", category.getId()),
                "name", category.getName(),
                "pid", category.getPid()
            ))
        ;
        if(count > 0){
            error(ERR_SAME_NAME);
        }
        db.getCollection(COL_CATEGORY)
            .replaceOne(bo("id", category.getId()), bo(category), new ReplaceOptions().upsert(true));
        return true;
    }

    public List<Category> getChildrenByPid(String pid){
        if(pid == null){
            pid = "";
        }
        var items = db.getCollection(COL_CATEGORY)
            .find(bo("pid", pid))
            .into(a());
        return cast(items, new TypeReference<List<Category>>(){});
    }

    public List<CategoryTree> getCategoryTree(){
        var items = db.getCollection(COL_CATEGORY)
            .find(bo())
            .into(a());
        return cast(toTree(items, "pid", "id", "sort"), new TypeReference<List<CategoryTree>>(){});
    }

    public List<Category> getAllCategories(){
        var items = db.getCollection(COL_CATEGORY)
            .find(bo())
            .into(a());
        return cast(items, new TypeReference<List<Category>>(){});
    }
}
